#pragma once
#include <cstdio>
#include <iostream>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include "comm.h"
#include <algorithm>

const std::string default_path = ".";
const int default_shmId = -1;
const int g_size = 4096;
const int default_proj_id = 066;
const int default_mode = 0666;

class shm
{
private:
    void CreateShmByType(int flag)
    {
        _shmid = shmget(_key, g_size, flag);
        if (_shmid < 0)
        {
            ERR_EXIT("CreateShmByType failed");
        }
        else
        {
            printf("CreateShmByType success\n");
        }
    }
    void Create()
    {
        CreateShmByType(IPC_CREAT | IPC_EXCL | default_mode);
    }
    void Get()
    {
        CreateShmByType(IPC_CREAT);
    }
    void destroy()
    {
        Detch();
        if ("creater" == _userType)
        {
            int n = shmctl(_shmid, IPC_RMID, nullptr);
            if (n < 0)
            {
                ERR_EXIT("destroy failed");
            }
            else
            {
                printf("destroy success!\n");
            }
        }
    }
    void Detch()
    {
        int n = shmdt(_start_addr);
        if (n == 0)
        {
            printf("Detch success\n");
        }
    }
    void Attach()
    {
        _start_addr = shmat(_shmid, nullptr, 0);
        if ((long long)_start_addr < 0)
        {
            ERR_EXIT("Attach failed");
        }
        else
        {
            printf("Attach success\n");
        }
    }

public:
    shm(const std::string &path,
        const int proj_id,
        const std::string &userType) : _shmid(default_shmId),
                                       _size(g_size), _userType(userType), _start_addr(nullptr)
    {
        _key = ftok(path.c_str(), proj_id);
        if (_key < 0)
        {
            ERR_EXIT("key");
        }
        else
        {
            printf("key create success\n");
        }
        std::transform(_userType.begin(), _userType.end(), _userType.begin(), ::tolower);
        if ("creater" == _userType)
        {
            Create();
        }
        else if ("user" == _userType)
        {
            Get();
        }
        Attach();
    };
    void *VisualAddr()
    {
        return _start_addr;
    }
    ~shm()
    {
        printf("角色: %s\n", _userType.c_str());
        if ("creater" == _userType)
            destroy();
    };

private:
    int _shmid;
    key_t _key;
    size_t _size;
    std::string _userType;
    void *_start_addr;
};
